<template>
  <div class="register-page">
    <BackgroundVideo />
    <div class="card">
      <div class="card-header">
        <h1>创建账户</h1>
        <p>加入我们的社区</p>
      </div>

      <!-- 主注册表单 -->
      <form @submit.prevent="handleRegister" class="form" v-if="!showVerification">
        <div class="form-group">
          <input type="text" id="username" v-model="username" required placeholder=" " class="input-field" />
          <label for="username" class="input-label">用户名</label>
        </div>

        <div class="form-group">
          <input type="email" id="email" v-model="email" required placeholder=" " class="input-field" />
          <label for="email" class="input-label">电子邮箱</label>
        </div>

        <div class="form-group">
          <input type="tel" id="phone" v-model="phone" required placeholder=" " class="input-field"
            @input="formatPhoneNumber" />
          <label for="phone" class="input-label">手机号码</label>
        </div>

        <div class="form-group">
          <input type="password" id="password" v-model="password" required placeholder=" " class="input-field" />
          <label for="password" class="input-label">密码</label>
        </div>

        <div class="form-group">
          <input type="password" id="confirmPassword" v-model="confirmPassword" required placeholder=" "
            class="input-field" />
          <label for="confirmPassword" class="input-label">确认密码</label>
        </div>

        <button type="submit" class="submit-btn">
          <span>获取验证码</span>
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M5 12h14M12 5l7 7-7 7" />
          </svg>
        </button>
      </form>

      <!-- 验证码验证表单 -->
      <form @submit.prevent="verifyCode" class="form" v-else>
        <div class="verification-notice">
          <p>验证码已发送至 {{ formattedPhone }}</p>
        </div>

        <div class="form-group verification-code-group">
          <input type="text" id="verificationCode" v-model="verificationCode" required placeholder=" "
            class="input-field" maxlength="6" />
          <label for="verificationCode" class="input-label">验证码</label>
          <button type="button" class="resend-btn" @click="sendVerificationCodeButton" :disabled="isCountingDown">
            {{ countdown > 0 ? `${countdown}秒后重发` : '重新发送' }}
          </button>
        </div>

        <div class="action-buttons">
          <button type="button" class="back-btn" @click="showVerification = false">
            返回修改
          </button>
          <button type="submit" class="submit-btn">
            <span>完成注册</span>
          </button>
        </div>
      </form>

      <div class="footer">
        <span>已有账户？</span>
        <router-link to="/login" class="login-link">立即登录</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { sendVerificationCode, verifyCaptcha, checkUsernameExists, register } from '@/api/login'
import BackgroundVideo from '@/components/BackgroundVideo.vue';

const router = useRouter();
const username = ref('');
const email = ref('');
const phone = ref('');
const password = ref('');
const confirmPassword = ref('');
const verificationCode = ref('');
const showVerification = ref(false);
const isCountingDown = ref(false);
const countdown = ref(0);

// 格式化显示的手机号
const formattedPhone = computed(() => {
  const num = phone.value.replace(/\D/g, '');
  return num.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3');
});

// 手机号自动格式化
const formatPhoneNumber = () => {
  phone.value = phone.value.replace(/\D/g, '');
  if (phone.value.length > 3 && phone.value.length <= 7) {
    phone.value = phone.value.replace(/(\d{3})(\d+)/, '$1 $2');
  } else if (phone.value.length > 7) {
    phone.value = phone.value.replace(/(\d{3})(\d{4})(\d+)/, '$1 $2 $3');
  }
};

// 发送验证码
const sendVerificationCodeButton = async () => {
  const phoneNumber = phone.value.replace(/\D/g, '');

  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
    alert('请输入有效的手机号码');
    return;
  }

  try {
    console.log('发送验证码', phoneNumber);
    const res = await sendVerificationCode(phoneNumber);

    if (res.code === 200) {
      startCountdown();
      showVerification.value = true;
    } else {
      alert('发送验证码失败: ' + res.msg);
    }
  } catch (error) {
    alert('发送验证码时出错');
    console.error(error);
  }
};

// 倒计时
const startCountdown = () => {
  isCountingDown.value = true;
  countdown.value = 60;

  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      isCountingDown.value = false;
    }
  }, 1000);
};

// 处理注册表单提交
const handleRegister = async () => {
  if (password.value !== confirmPassword.value) {
    alert('密码不匹配');
    return;
  }
  // 验证用户名是否存在

  try {
    const res = await checkUsernameExists(username.value)
    console.log('验证用户名', res)
    if (res.data) {
      alert('用户名已存在')
      return;
    }
  } catch (error) {
    console.error('验证用户名出错:', error)
    alert('验证用户名时出错')
  }

  // 验证其他必填字段
  if (!username.value || !email.value || !phone.value) {
    alert('请填写所有必填字段');
    return;
  }


  await sendVerificationCodeButton();
};

// 验证验证码并完成注册
const verifyCode = async () => {
  if (!verificationCode.value || verificationCode.value.length !== 4) {
    alert('请输入4位验证码');
    return;
  }

  try {
    const verifyRes = await verifyCaptcha({
      phone: phone.value.replace(/\D/g, ''),
      captcha: verificationCode.value
    });

    if (verifyRes.code !== 200) {
      alert('验证码错误或已过期');
      return;
    }

    // 验证通过后完成注册
    const registerRes = await register({
      username: username.value,
      password: password.value,
      email: email.value,
      phone: phone.value.replace(/\D/g, ''),
      captcha: verificationCode.value
    });

    if (registerRes.code === 200) {
      alert('注册成功');
      router.push('/login');
    } else {
      alert('注册失败: ' + registerRes.msg);
    }
  } catch (error) {
    alert('注册过程中出现错误');
    console.error(error);
  }
};
</script>

<style scoped>
/* 原有样式保持不变 */
.register-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 2rem;
  position: relative;
  overflow: hidden;
}

.card {
  width: 100%;
  max-width: 420px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 2.5rem;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  z-index: 1;
  transform: translateY(0);
  transition: transform 0.3s ease;
}

.card:hover {
  transform: translateY(-5px);
}

.card-header {
  text-align: center;
  margin-bottom: 2rem;
}

.card-header h1 {
  font-size: 1.8rem;
  font-weight: 700;
  color: #2d3748;
  margin-bottom: 0.5rem;
}

.card-header p {
  color: #718096;
  font-size: 0.9rem;
}

.form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.form-group {
  position: relative;
}

.input-field {
  width: 100%;
  padding: 1rem;
  font-size: 1rem;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background-color: #f8fafc;
  transition: all 0.3s ease;
  outline: none;
}

.input-field:focus {
  border-color: #4299e1;
  box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.2);
}

.input-field:focus+.input-label,
.input-field:not(:placeholder-shown)+.input-label {
  transform: translateY(-1.5rem) scale(0.85);
  background-color: white;
  padding: 0 0.5rem;
  left: 0.8rem;
  color: #4299e1;
}

.input-label {
  position: absolute;
  left: 1rem;
  top: 1rem;
  color: #718096;
  pointer-events: none;
  transition: all 0.3s ease;
  transform-origin: left center;
}

.submit-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  width: 100%;
  padding: 1rem;
  background-color: #4299e1;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 1rem;
}

.submit-btn:hover {
  background-color: #3182ce;
  transform: translateY(-2px);
}

.submit-btn:active {
  transform: translateY(0);
}

.submit-btn svg {
  transition: transform 0.3s ease;
}

.submit-btn:hover svg {
  transform: translateX(3px);
}

.footer {
  text-align: center;
  margin-top: 1.5rem;
  color: #718096;
  font-size: 0.9rem;
}

.login-link {
  color: #4299e1;
  text-decoration: none;
  font-weight: 600;
  transition: color 0.2s ease;
}

.login-link:hover {
  color: #3182ce;
  text-decoration: underline;
}

@media (max-width: 480px) {
  .card {
    padding: 1.5rem;
  }
}

.verification-notice {
  text-align: center;
  margin-bottom: 1.5rem;
  color: #4a5568;
  font-size: 0.95rem;
}

.verification-notice p {
  margin: 0;
}

.verification-code-group {
  position: relative;
}

.resend-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #4299e1;
  font-size: 0.85rem;
  cursor: pointer;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.resend-btn:hover:not(:disabled) {
  background-color: rgba(66, 153, 225, 0.1);
}

.resend-btn:disabled {
  color: #a0aec0;
  cursor: not-allowed;
}

.action-buttons {
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
}

.back-btn {
  flex: 1;
  padding: 1rem;
  background-color: #f8fafc;
  color: #2d3748;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background-color: #edf2f7;
}

/* 动画效果 */
.form {
  transition: all 0.3s ease;
}
</style>